package com.itheima.health.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.health.util.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class FileTask {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 每天一点执行清理OSS中垃圾图片
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void fileTask() {
        log.info("开始清理OSS垃圾图片");
        //1.查询OSS中的图片
        List<String> ossImageList = aliOssUtil.getFileList();
        //2.查询redis中套餐的图片集合
        String cacheKey = "health-setmeal";
        String setmealsJson = redisTemplate.opsForValue().get(cacheKey);
        List<String> imagesList = new ArrayList<>();
        if (setmealsJson != null && !"".equals(setmealsJson)) {
            JSONObject jsonObject = JSON.parseObject(setmealsJson);
            JSONArray rowsArray = jsonObject.getJSONArray("rows");
            for (int i = 0; i < rowsArray.size(); i++) {
                JSONObject setmealJson = rowsArray.getJSONObject(i);
                String img = setmealJson.getString("img");
                imagesList.add(img);
            }
        }
        List<String> dbImageList = new ArrayList<>();
        //截取图片url
        for (String image : imagesList) {
            String[] parts = image.split("/");
            String lastPart = parts[parts.length - 1];
            dbImageList.add(lastPart);
        }
        //3.对比出不同数据批量删除
        List<String> invalidImageList = dbImageList.stream().filter(image -> !ossImageList.contains(image)).collect(Collectors.toList());
        List<String> invalidImage = ossImageList.stream().filter(image -> !dbImageList.contains(image)).collect(Collectors.toList());
        invalidImageList.addAll(invalidImage);
        aliOssUtil.deleteFile(invalidImageList);
        log.info("完成清理OSS垃圾图片");
    }
}
